package absc.wizard;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;

import absc.util.CreateWorkspace;

public class ABSCWizard extends Wizard implements INewWizard {

	private WizardNewProjectCreationPage mainPage;
	private ABSCWizardMySqlPage mySqlPage;
	
	public ABSCWizard() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean performFinish() {
		createNewProject();
		
		return true;
	}

	private void createNewProject() {
		final IProject newProject; 
		final IProjectDescription description;
		
		newProject = mainPage.getProjectHandle();
		description = createProjectDescription(newProject);
		
		WorkspaceModifyOperation op = new CreateWorkspace(newProject, description, this.mySqlPage.getConexaoBanco());
		
		runProjectCreationOperation(op, newProject);
	}
	
	private void runProjectCreationOperation(WorkspaceModifyOperation op, IProject newProjectHandle) {
		try {
			getContainer().run(false, true, op);
		} catch (Exception e) {
			e.printStackTrace();
			MessageDialog.openError(getShell(), "Creation Problems", "An error occur during the installation of ABSC MySql database");
		}
	}

	private IProjectDescription createProjectDescription(IProject newProjectHandle) {
		IPath newPath;
		IWorkspace workspace;
		IProjectDescription description;
		
		newPath = null;
		
		if (!mainPage.useDefaults())
			newPath = mainPage.getLocationPath();
		
		workspace = ResourcesPlugin.getWorkspace();
		description = workspace.newProjectDescription(newProjectHandle.getName());
		description.setLocation(newPath);		
		
		return description;
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		setNeedsProgressMonitor(true);
		setWindowTitle("New ABSC Project");
	}

	public void addPages() {
		addMainPage();
		addMySqlPage();
	}

	private void addMySqlPage() {
		this.mySqlPage = new ABSCWizardMySqlPage();
		addPage(this.mySqlPage);
	}

	private void addMainPage() {
		super.addPages();
		setWindowTitle("New ABSC Project");
		mainPage = new WizardNewProjectCreationPage("basicNewProjectPage");		
		mainPage.setTitle("ABSC Project");
		mainPage.setDescription("Create a new ABSC project.");
		addPage(mainPage);
	}
}
